import socket
import logging
import os

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

class MultiNodeConfig:
    REDIS_PORT = 6379
    REDIS_DB = 0
    HEARTBEAT_TIMEOUT = 60
    MASTER_PORT = 5000
    ISO_DIR1 = os.getenv("ISO_DIR", "/mnt/nfs_client")  # ISO文件目录，默认为/mnt/nfs_client
    ISO_DIR2 = os.getenv("ISO_DIR", "/data/nfs_share")  
    # 用于存储 Master 节点的 IP，默认为 None
    MASTER_IP = os.getenv("MASTER_IP", None)  # 可以通过环境变量设置

    @staticmethod
    def get_local_ip():
        """获取本机IP地址"""
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        try:
            s.connect(('8.8.8.8', 1))
            ip = s.getsockname()[0]
        except Exception as e:
            logger.error(f"Failed to get local IP: {str(e)}")
            ip = '127.0.0.1'
        finally:
            s.close()
        logger.info(f"Detected local IP: {ip}")
        return ip

    @staticmethod
    def get_redis_host(role=None):
        """根据角色返回 Redis 主机地址，并记录日志"""
        if role == "master":
            redis_host = MultiNodeConfig.get_local_ip()
            logging.info(f"Detected role as 'master'. Returning local IP as Redis host: {redis_host}")
            return redis_host
        elif role == "worker":
            if MultiNodeConfig.MASTER_IP:
                redis_host = MultiNodeConfig.MASTER_IP
                logging.info(f"Detected role as 'worker'. Returning master node's IP as Redis host: {redis_host}")
                return redis_host
            else:
                logging.error("MASTER_IP not specified for worker node.")
                raise ValueError("MASTER_IP not specified for worker node. Set MASTER_IP environment variable or pass --master-ip argument.")
        else:
            redis_host = MultiNodeConfig.get_local_ip()
            logging.info(f"No specific role detected. Assuming initialization mode and returning local IP as Redis host: {redis_host}")
            return redis_host